package com.gong.chooselesson.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gong.chooselesson.mapper.LessonMapper;
import com.gong.chooselesson.mapper.SlMapper;
import com.gong.chooselesson.pojo.Lesson;
import com.gong.chooselesson.pojo.Sl;
import com.gong.chooselesson.service.SlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;

/**
 * @Description
 * @Author gongchang
 * @Date 2021-07-27 16:38
 */
@Service
public class SlServiceImpl extends ServiceImpl<SlMapper, Sl> implements SlService {

    @Autowired
    Jedis readJedis;
    @Autowired
    Jedis writeJedis;
    @Autowired
    SlMapper slMapper;
    @Autowired
    LessonMapper lessonMapper;

    @Override
    public boolean iscroth(int lno, int sno){
        //判断redis中是否有目标学生的选课情况
        Set<String> keys = readJedis.keys("sno:" + sno);
        Lesson lesson = lessonMapper.selectById(lno);

        boolean res = true;
        if (keys.isEmpty()){//没有，则从数据库中查找，并放入redis
            List<Integer> list = slMapper.getLnoBySno(sno);
            for (Integer integer : list) {
                if (integer == lesson.getLNo()){
                    res = false;
                }
                writeJedis.setbit("sno:"+sno,integer, String.valueOf(1));
            }
        }else {//有，则获取对应数据，判断冲突
            Boolean getbit = readJedis.getbit( "sno:" + sno,lesson.getLNo());
            if (getbit){
                res = false;
            }else {
                res = true;
            }
        }

        return res;
    }
}
